// $Id$
// Licensed under Apache License Version 2.0
// See: http://www.apache.org/licenses/LICENSE-2.0.html
package de.servicezombie.tcmdb.util.validations;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;

import de.servicezombie.tcmdb.TcmdbValidationFailedException;
import de.servicezombie.tcmdb.rest.vo.WsTestExecution;

public class ValidateTestExecutionBeforeSave implements Validation<WsTestExecution> {

	private static final Logger log = LoggerFactory.getLogger(ValidateTestExecutionBeforeSave.class);

	private ValidateTestExecutionResolution validateTestExecutionResolution;

	public void setValidateTestExecutionResolution(ValidateTestExecutionResolution validateTestExecutionResolution) {
		this.validateTestExecutionResolution = validateTestExecutionResolution;
	}

	@Override
	public void validate(WsTestExecution bean) throws TcmdbValidationFailedException {
		assertNotNull(bean, "referencedDefinitionId");
		validateTestExecutionResolution.validate(bean.getResolution());
	}

	private void assertNotNull(Object bean, String property) {
		boolean fail = true;
		if (bean != null) {
			try {
				PropertyDescriptor pd = BeanUtils.getPropertyDescriptor(bean.getClass(), property);
				Method m = pd.getReadMethod();
				Object value = m.invoke(bean);
				fail = value == null;
			}
			catch (Exception e) {
				log.warn("Unable to read property " + bean.getClass().getName() + "#" + property + "(" + e.getMessage() + ")");
				if (log.isDebugEnabled()) {
					log.debug("assertNotNull: stacktrace dump", e);
				}
			}
		}

		if (fail) {
			throw new TcmdbValidationFailedException("Property " + property + " is null on bean " + bean)
					.withValidatedBean(bean);
		}
	}

}
